
// packageI/worker/index/index.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    btn_loading: false,
    btn_disabled: false,
    btn_loading_text: "提交中..",
    checked: false,
    register_type: [], //注册支付类型
    register_type_list: [1,2],
    showPicker: false,
    agree: false,
    columns: ["居民身份证", "港澳居民来往内地通行证", "台胞证"],
    identity_card_front: {},
    identity_card_backend: {},
    show_agreement: false, //显示协议
    showSex: false, //性别
    showBirth: false, //出生日期
    info: {
      name: "",
      mobile: "",
      identity_card_no: "",
      identity_card_type: "",
      identity_card_front: "",
      identity_card_backend: "",
      gender: "",
      birthday: ""
    },
    //性别
    sexList: ["男", "女"],
    //日期
    minDate: new Date(1900, 0, 1).getTime(),
    maxDate: new Date(2030, 12, 31).getTime(),
    currentDate: new Date().getTime(),
    redirect: false,
    //协议文本
    desc: "",
    register_type_Id:null,
    path:"",
    plugNmae:'worker_withdraw',
    // 银行卡信息
    bank: "",
    bank_branch:"",
    // 支付宝信息
    alipay: "",
    // radio: "1",
    sexLIst: [{ //性别选择列表
      value: "男",
      url: `${app.globalData.imgPath}debt/manNo.png`,
      checkedUrl: `${app.globalData.imgPath}debt/manYes.png`,
      checked: false
    }, {
      value: "女",
      url: `${app.globalData.imgPath}debt/womenNo.png`,
      checkedUrl: `${app.globalData.imgPath}debt/womenYes.png`,
      checked: false
    }],
    imgPath: app.globalData.imgPath,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.name){
      this.setData({
        plugNmae:options.name
      })
      this.hJGetData();
      return
    }
    this.setData({path:options.path||''})
    if(options.register_type_Id){
      this.data.register_type.push(options.register_type_Id);
      this.setData({register_type:this.data.register_type,register_type_Id:options.register_type_Id});
    }
    this.getData();
    this.checkAllHandle()
  },
  choose(e){
    this.setData({
      register_type:e.detail
    })
    if(this.data.register_type.length==2){
      this.setData({
        checked:true,
      })
    }else{
      this.setData({
        checked:false
      })
    }
  },
  onChange(){
    this.setData({
      checked:!this.data.checked
    })
    if(this.data.checked){
      const checkbox1 = this.selectComponent(`.checkboxGroup-0`);
      const checkbox2 = this.selectComponent(`.checkboxGroup-1`);
      if(this.data.register_type.length == 1){
        let index = this.data.register_type[0]-1;
        const checkbox= this.selectComponent(`.checkboxGroup-${index}`);
        checkbox.toggle()
      }else{
        checkbox1.toggle();
        checkbox2.toggle();
      }
      this.setData({
        register_type:["1","2"],
        checked:true
      })
    }else{
      this.setData({
        register_type:[],
        checked:false
      })
    }
  },
  checkAllHandle(){

  },
  getData(){
    app._postNetWork({
      url:app.getNetAddresss("plugin.worker-withdraw.frontend.register.page"),
      data:{
        register_type:this.data.register_type_Id
      },
      success:res=>{
        if(res.data.result ==1){
          let data = res.data.data.register_data;
          this.setData({desc:res.data.data.desc})
          if(data){
            this.setData({
              "info.name":data.name,
              "info.mobile":data.mobile,
              "info.identity_card_no":data.identity_card_no,
              "info.identity_card_front":data.identity_card_front,
              "info.identity_card_backend" : data.identity_card_backend,
              "info.birthday" : data.birthday
            })
            if (data.identity_card_type == "1") {
              this.setData({
                "info.identity_card_type":"居民身份证"
              })
            } else if (data.identity_card_type == "2") {
              this.setData({"info.identity_card_type":"港澳居民来往内地通行证"})
            } else {
              this.setData({
                "info.identity_card_type":"台胞证"
              })
            }
            if (data.gender == 0) {
              this.setData({
                "info.gender":"女"
              })
            } else {
              this.setData({
                "info.gender":"男"
              })
            }
            this.setData({
              identity_card_backend:[{url: data.identity_card_backend_url}],
              identity_card_front:[{url: data.identity_card_front_url}]
            })
          }
          if (res.data.data.register_type.length !== 0) {
            this.setData({
              register_type_list:res.data.data.register_type
            })
          }
        }else{
          app.tips(res.data.msg);
        }
      }
    })
  },
  onClose(event){
    let filed =  event.currentTarget.dataset.filed;
    this.setData({
      [filed]:false
    })
  },
  inputText(event){
    let filed = event.currentTarget.dataset.filed,
    value = event.detail;
    let info= `info.${filed}`;
    this.setData({
      [info]:value
    })
  },
  agreement(){
    this.setData({show_agreement:false})
  },
    confirmBirth(value) {
      console.log(value)
      let date = new Date(value.detail);
      let years = date.getFullYear(),
        month = date.getMonth() + 1,
        day = date.getDate();
      if (month < 10) {
        month = `0${month}`;
      }
      if (day < 10) {
        day = `0${day}`;
      }
      this.setData({
        "info.birthday":`${years}-${month}-${day}`,
        showBirth:false
      })
    },
    afterRead(event) {
      let {file} = event.detail;
      let urlStr = app.getNetAddresss('upload.uploadPic');
      wx.uploadFile({
        url: urlStr,
        filePath: file.url,
        name: 'file',
        formData: null,
        success:(res)=> {
          let _res =JSON.parse(res.data);
          this.setData({
            identity_card_backend:[{url:_res.data.img_url}],
            "info.identity_card_backend": this.data.plugNmae == 'tax_withdraw_bank' ? _res.data.img : _res.data.img_url
          })
        },
      });
    },
    deletePhotoFront(){
      this.setData({identity_card_front:[],"info.identity_card_front":""})
    },
    deletePhotoBackend(){
      this.setData({identity_card_backend:[],"info.identity_card_backend":""})
    },
    onRead_2(event) {
      let {file} = event.detail;
      let urlStr = app.getNetAddresss('upload.uploadPic');
      wx.uploadFile({
        url: urlStr,
        filePath: file.url,
        name: 'file',
        formData: null,
        success:(res)=> {
          let _res =JSON.parse(res.data);
          this.setData({
            identity_card_front:[{url:_res.data.img_url}],
            "info.identity_card_front":this.data.plugNmae == 'tax_withdraw_bank' ? _res.data.img : _res.data.img_url
          })
        },
      });
    },
    closePop(e){
      let type = e.currentTarget.dataset.filed;
      this.setData({
        [type]:true
      })
    },
    popup(e){
      let type = e.currentTarget.dataset.filed;
      this.setData({
        [type]:true
      })
    },
    tax_withdraw_bank_Submit(){
      let json = {
        realname: this.data.info.name,
        mobile: this.data.info.mobile,
        idcard: this.data.info.identity_card_no,
        idcard_front: this.data.info.identity_card_front,
        idcard_back: this.data.info.identity_card_backend,
        bank: this.data.bank,
        bank_branch: this.data.bank_branch
      };
      let text = {
        name: "请输入姓名",
        mobile: "请输入手机号",
        identity_card_no: "请输入身份证件号",
        identity_card_front: "请上传身份证(人像面)",
        identity_card_backend: "请上传身份证(国徽面)",
        bank:"请填写银行卡号",
        bank_branch:"请填写银行开户行"
      };
      for (const key in text) {
        if (this.data.info[key] == "") {
          app.tips(text[key]);
          return
        }else if ( app._isTextEmpty(this.data.info.identity_card_front) ){
          app.tips(text.identity_card_front);
          return
        }else if ( app._isTextEmpty(this.data.info.identity_card_backend) ){
          app.tips(text.identity_card_backend);
          return
        }else if ( app._isTextEmpty(this.data.bank) ){
          app.tips(text.bank);
          return
        }else if ( app._isTextEmpty(this.data.bank_branch)) {
          app.tips(text.bank_branch)
        }
      }
      this.setData({
        btn_loading:true,
        btn_loading_text:"正在提交...",
        btn_disabled:true
      })
      console.log(json)
      app._postNetWork({
        url:app.getNetAddresss("plugin.tax-withdraw.frontend.member-info.set"),
        data:json,
        success:res=>{
          app.tips(res.data.msg)
          if(res.data.result ==1){
            wx.navigateBack({
              delta:1
            })
            this.hJGetData();
          }
        },
        complete:res=>{
          this.setData({
            btn_disabled:false,
            btn_loading_text:"",
            btn_loading:false
          })
        }
      })
    },
    onSubmit() {
      if(this.data.plugNmae == 'tax_withdraw_bank'){
        this.tax_withdraw_bank_Submit();
        return
      }
      if(this.data.plugNmae == 'hJwithdrawType'){
        // 汇聚代发薪插件
        // if (app._isTextEmpty(this.data.bank)) {
        //   return app.tips("请填写银行卡号");
        // }
        // if (app._isTextEmpty(this.data.alipay)) {
        //   return app.tips("请填写支付宝信息");
        // }
        let json = {
          realname: this.data.info.name,
          mobile: this.data.info.mobile,
          idcard: this.data.info.identity_card_no,
          bank: this.data.bank,
          card_front: this.data.info.identity_card_front,
          card_back: this.data.info.identity_card_backend,
          // bank_name: this.data.radio == 1 ? "招商银行" : "平安银行",
          alipay: this.data.alipay
        };
        console.log(json,'dwwwwww')
        this.data.info.gender == "男" ? (json.gender = 1) : (json.gender = 2);
        let text = {
          name: "请输入姓名",
          mobile: "请输入手机号",
          identity_card_no: "请输入身份证号码",
          gender: "请选择性别",
          identity_card_front: "请上传身份证(人像面)",
          identity_card_backend: "请上传身份证(国徽面)"
        };
        for (const key in text) {
          console.log(this.data.info[key])
          if (app._isTextEmpty(this.data.info[key])) {
            return app.tips(text[key]);
          }
        }
        if (this.data.info.mobile.length < 11) {
          return app.tips("请输入正确的手机号");
        }

        const validateChineseName = (name) => {
          const regex = /^[\u4E00-\u9FA5]{2,}(?:·[\u4E00-\u9FA5]{2,})*$/;
          return regex.test(name);
        };//用于验证中国身份证姓名

        const validateXinjiangIDName = (name) => {
          const regex = /^[\u4E00-\u9FA5]{2,}(?:[.·]{1}[\u4E00-\u9FA5]{2,})*$/;
          return regex.test(name);
        };//用于验证中国xinjian身份证姓名
        if (!(validateChineseName(this.data.info.name)||validateXinjiangIDName(this.data.info.name))) {
          return app.tips("请输入真实姓名");
        }
        this.postPaySet(json);
        return
      }
      if (!this.data.agree) {
        return app.tips("请勾选服务协议");
      }
        if ( this.data.register_type.length == 0) {
        return app.tips("请选择注册类型");
      }
      let json = {
        name: this.data.info.name,
        mobile: this.data.info.mobile,
        identity_card_no: this.data.info.identity_card_no,
        identity_card_front: this.data.info.identity_card_front,
        identity_card_backend: this.data.info.identity_card_backend,
        birthday: this.data.info.birthday
      };
      json.register_type = this.data.register_type.length == 2 ? [-1] : this.data.register_type;

      this.data.info.gender == "男" ? (json.gender = 1) : (json.gender = 0);
      this.data.info.identity_card_type == "居民身份证"
        ? (json.identity_card_type = 1)
        : this.data.info.identity_card_type == "港澳居民来往内地通行证"
        ? (json.identity_card_type = 2)
        : (json.identity_card_type = 3);
      let text = {
        name: "请输入姓名",
        mobile: "请输入手机号",
        identity_card_type: "请选择身份证类型",
        identity_card_no: "请输入证件号",
        gender: "请选择性别",
        birthday: "请选择出生日期",
        identity_card_front: "请上传身份证(人像面)",
        identity_card_backend:"请上传身份证(国徽面)"
      };
      for (const key in text) {
        if (this.data.info[key] == "") {
          return app.tips(text[key]);
        }
      }
      if (this.data.info.mobile.length < 11) {
        return app.tips("请输入正确的手机号");
      }
      let reg = /^[\u4e00-\u9fa5]{2,6}$/;
      if (!reg.test(this.data.info.name)) {
        return app.tips("请输入真实姓名");
      }
      this.setData({
        btn_loading:true,
        btn_loading_text:"正在提交...",
        btn_disabled:true
      })
      app._postNetWork({
        url:app.getNetAddresss("plugin.worker-withdraw.frontend.register.index"),
        data:json,
        success:res=>{
          app.tips(res.data.msg)
          if(res.data.result ==1){
           if(this.data.path == 'balance_withdrawals'){
            wx.navigateTo({
              url: '/packageA/member/balance/balance_withdrawals/balance_withdrawals',
            })
           }else if(this.data.path=='withdrawal'){
             wx.navigateTo({
               url: '/packageA/member/withdrawal/withdrawal',
             })
           }else if(this.data.path == 'loveWithdrawal'){
            wx.navigateTo({
              url: '/packageB/member/love/loveWithdrawals/loveWithdrawals',
            })
           }else{
             wx.navigateTo({
               url: '/packageG/member_v2/member_v2',
             })
           }
          }
        },
        complete:res=>{
          this.setData({
            btn_disabled:false,
            btn_loading_text:"",
            btn_loading:false
          })
        }
      })
    },
    onConfirm(event) {
      this.setData({
        "info.identity_card_type":event.detail.value,
        showPicker:false
      })
    },
    onConfirmGender(event) {
      this.setData({
        "info.gender":event.detail.value,
        showSex:false
      })
    },
  onAgreement(){
    this.setData({
      show_agreement:true
    })
  },
  ready(){
    this.setData({agree:!this.data.agree})
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if(this.options.name == 'hJwithdrawType'){
      var pages = getCurrentPages(); //获取加载的页面
      if(pages.length > 1){
        // var currentPage = pages[pages.length - 2]; //获取当前页面的对象
        let formTo = pages[pages.length - 2].route
        if(formTo != 'packageG/member_v2/member_v2' || formTo != 'packageG/morePlugin/morePlugin'){
          this.data.isMemberInto = true;
        }else{
          this.data.isMemberInto = false;
        }
      }
    }
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 汇聚代发薪
  hJGetData(){
    let _url = app.getNetAddresss("plugin.consol-withdraw.frontend.member-info.index");
    if(this.data.plugNmae == 'tax_withdraw_bank'){
      _url = app.getNetAddresss("plugin.tax-withdraw.frontend.member-info.index")
    }
    app._postNetWork({
      url:_url,
      data:{},
      success:res=>{
        let _data = res.data.data;
        if(res.data.result ==1){
          if(this.data.plugNmae == 'tax_withdraw_bank'){
            this.setData({
              'info.name':_data.member.realname,
              'info.mobile':_data.member.mobile,
              'info.identity_card_no':_data.member.idcard,
              'info.identity_card_front':_data.member.idcard_front,
              'info.identity_card_backend':_data.member.idcard_back,
              bank:_data.bank.bank_card,
              bank_branch:_data.bank.bank_branch
            })
            this.data.identity_card_front[0] = _data.member.idcard_front;
            this.data.identity_card_backend[0] = _data.member.idcard_back;
            this.setData({
              identity_card_backend:this.data.identity_card_backend,
              identity_card_front:this.data.identity_card_front
            })
            wx.setNavigationBarTitle({
              title: '税筹添薪签约',
            })
            return
          }
          wx.setNavigationBarTitle({
            title: '汇聚代发薪签约',
          })
          this.setData({
            "info.name":_data.realname,
            "info.mobile":_data.mobile,
            "info.identity_card_no":_data.idcard,
            bank:_data?.bank?.bank_card || "",
            "info.gender":_data.gender == 1 ? "男" : "女",
            "info.identity_card_front":_data?.idcard_info?.card_front,
            "info.identity_card_backend":_data?.idcard_info?.card_back,
            alipay:_data.alipay
          })
          // if(_data.bank && (_data.bank.bank_name == "招商银行" || _data.bank.bank_name == "平安银行")){
          //   if (_data.bank.bank_name == "招商银行") {
          //     this.setData({
          //       radio:"1"
          //     })
          //   } else if (_data.bank.bank_name == "平安银行") {
          //     this.setData({
          //       radio:"2"
          //     })
          //   }
          // }else{
          //   this.setData({
          //     radio:'',
          //     bank:''
          //   })
          // }
          if (_data.gender == 1) {
            this.sexSwitch(0);
          } else {
            this.sexSwitch(1);
          }
        }else{
          app.tips(res.data.msg);
        }
      }
    })
  },
  sexPopup(){
    this.setData({
      showSex:false
    })
  },
  sexSwitch(e) { //性别切换
    let keyInd = e.currentTarget ? e.currentTarget.dataset.index : e;
    this.data.sexLIst.forEach((item, index) => {
      let sexListIndex = `sexLIst[${index}].checked`
      if (keyInd == index) {
        this.setData({
          [sexListIndex]: true
        })
        if (keyInd == 1) {
          this.setData({
            'info.gender': "女"
          })
        } else {
          this.setData({
            'info.gender': "男"
          })
        }
      } else {
        this.setData({
          [sexListIndex]: false
        })
      }
    })
  },
  postPaySet(json){
    this.setData({
      btn_loading:true,
      btn_loading_text:"正在提交...",
      btn_disabled:true
    })
    app._postNetWork({
      url:app.getNetAddresss("plugin.consol-withdraw.frontend.member-info.set"),
      data:json,
      success:res=>{
        app.tips(res.data.msg)
        if(res.data.result ==1){
          console.log(res.data)
          if(this.data.isMemberInto){
            this.hJGetData();
          }else{
            wx.navigateBack({
              delta: 1,
              success: (res) => {},
              fail: (res) => {
                wx.navigateTo({
                  url: '/packageG/member_v2/member_v2',
                })
              },
              complete: (res) => {},
            })
          }
        }
      },
      complete:res=>{
        this.setData({
          btn_disabled:false,
          btn_loading_text:"",
          btn_loading:false
        })
      }
    })
  }
})